package com.myrent.controller;

import com.myrent.common.ReturnData;
import com.myrent.entity.EnterpriseMerchant;
import com.myrent.service.EnterpriseService;
import com.myrent.utils.JwtTokenUtil;
import com.myrent.utils.RedisUtil;
import com.myrent.utils.ValidatedUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Validated
@Slf4j
public class EnterpriseController {

    @Autowired
    EnterpriseService service;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 企业的注册。
     * 让管理员去审核
     */
    @RequestMapping("/enterprise/register")
    public ReturnData enterpriseRegister(EnterpriseMerchant enterpriseMerchant) {
        if (!ValidatedUtil.validate(enterpriseMerchant)) {
            return ReturnData.fail(-2, "请检查参数条件");
        }
        try {
            //应该要先查询再返回结果。这里数据库加了唯一约束（email shopName）
            boolean b = service.register(enterpriseMerchant);
            if (b) {
                return ReturnData.success();
            }
            return ReturnData.fail(-1, "注册失败,考虑重名的情况.店铺名称和email不可以重复");
        } catch (Exception e) {
            return ReturnData.fail(-1, "注册失败,考虑重名的情况，店铺名称和email不可以重复");
        }
    }

    @PostMapping("/enterprise/login")
    public ReturnData enterpriseLogin(EnterpriseMerchant enterprise, HttpServletRequest request) {
        if (!ValidatedUtil.validate(enterprise)) {
            return ReturnData.fail(-2, "格式错误（邮箱或者密码）");
        }
        Boolean b = service.login(enterprise.getEShopEmail(), enterprise.getEShopPassword());
        if (b) {
            enterprise = service.getEnterprise(enterprise.getEShopEmail());
            try {
                //生成一个随机的不重复的uuid
                UUID uuid = UUID.randomUUID();
                String token = JwtTokenUtil.createToken(null, enterprise.getEShopId(), uuid.toString());
                enterprise.setEShopPassword(null);
                enterprise.setSalt(null);
                redisUtil.set("shop:" + enterprise.getEShopId(), uuid.toString(), 60 * 60 * 24 * 7L);
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("token", token);
                map.put("enterprise", enterprise);
                return ReturnData.success(map);
            } catch (Exception e) {
                log.info("登录失败{}", e.getMessage());
            }
        }
        return ReturnData.fail(-1, "登入失败,请检查企业邮箱或密码");
    }


}
